Skip to main content

Convert String to String[] in Java

Banner java icon

๐Ÿคนโ€โ™‚๏ธ Java String to String Array (and Back!) โ€“ The Fun Wayโ€‹

Ever wanted to break a string into tiny little pieces and then put it back together like a digital puzzle? Java's got you covered! Let's dive into the magical world of String.split() and Pattern.split() โ€“ and then, like a good magician, we'll bring it all back with String.join()! ๐ŸŽฉโœจ


๐Ÿ”ฅ Breaking Strings Apart (String โž String Array)โ€‹

1๏ธโƒฃ Using String.split() โ€“ The Easy Wayโ€‹

Just like slicing a pizza ๐Ÿ•, split() lets you divide a string into multiple pieces based on a delimiter.

String names = "alex,brian,charles,david";

String[] namesArray = names.split(","); // [alex, brian, charles, david]

Boom! You've got an array of names, ready for action. ๐Ÿš€


2๏ธโƒฃ Using Pattern.split() โ€“ The Regex Ninja Move ๐Ÿคบโ€‹

If you like things fancy, you can use Pattern.split() instead. Think of it like wielding a lightsaber instead of a butter knife. โš”๏ธ

String names = "alex,brian,charles,david";

Pattern pattern = Pattern.compile(",");
String[] namesArray = pattern.split(names); // [alex, brian, charles, david]

It does the same thing but allows for more complex pattern matching. Imagine splitting a string based on multiple delimiters โ€“ yeah, it's that powerful! ๐Ÿ’ช


๐Ÿงฉ Putting Strings Back Together (String Array โž String)โ€‹

Now, let's reverse the magic trick and reassemble our strings with String.join()!

String[] tokens = {"How", "To", "Do", "In", "Java"};

String blogName1 = String.join("", tokens); // HowToDoInJava
String blogName2 = String.join(" ", tokens); // How To Do In Java
String blogName3 = String.join("-", tokens); // How-To-Do-In-Java

Whether you like your words squished together, spaced out, or dashed up, String.join() has your back! ๐Ÿ’ฅ


๐Ÿ† Conclusionโ€‹

Splitting and joining strings in Java is like playing with LEGO bricks โ€“ break them apart and snap them back together however you like! ๐Ÿงฑ

๐Ÿ’ฌ Got questions? Drop them in the comments below!

Happy Coding! ๐ŸŽ‰